package com.study.talk.adapter;

import android.annotation.SuppressLint;
import android.view.ViewGroup;
import android.widget.PopupMenu;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.study.talk.R;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.databinding.MomentListCommentItemBinding;
import com.study.talk.entity.MomentComment;
import com.study.talk.net.NetApi;
import com.study.talk.util.ToastUtil;

import java.util.ArrayList;

public class MomentCommentListAdapter extends RecyclerView.Adapter<MomentCommentListAdapter.ViewHolder> {

    public static class ViewHolder extends RecyclerView.ViewHolder {
        MomentListCommentItemBinding viewBinding;

        public ViewHolder(@NonNull MomentListCommentItemBinding viewBinding) {
            super(viewBinding.getRoot());
            this.viewBinding = viewBinding;
        }
    }

    ArrayList<MomentComment> data;

    BaseActivity activity;

    public MomentCommentListAdapter(ArrayList<MomentComment> data, BaseActivity activity) {
        this.data = data;
        this.activity = activity;
    }

    /** 创建ViewHolder */
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(MomentListCommentItemBinding.inflate(activity.getLayoutInflater(), parent, false));
    }


    /** 绑定ViewHolder 数据 */
    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MomentComment comment = data.get(position);
        holder.viewBinding.momentListCommentItemTextView.setText(data.get(position).getUserName() + ": " + data.get(position).getContent());
        // 设置评论列表项的长按事件
        holder.viewBinding.getRoot().setOnLongClickListener(v -> {
            // 创建弹出菜单
            PopupMenu popupMenu = new PopupMenu(activity, v);
            popupMenu.getMenuInflater().inflate(R.menu.delete, popupMenu.getMenu());
            popupMenu.show();
            // 设置菜单项的点击事件
            popupMenu.setOnMenuItemClickListener(item -> {
                if (item.getItemId() == R.id.menu_delete) {
                    // 删除评论
                    NetApi.deleteMomentComment(comment, b -> {
                        data.remove(position);
                        activity.runOnUiThread(() -> notifyItemRemoved(position));
                    }, msg -> activity.runOnUiThread(() -> ToastUtil.showToast(activity, msg)));
                }
                return true;
            });
            return true;
        });
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

}
